package com.jsits.v2x.common.connection.socket;

import com.jsits.v2x.common.timer.TimerMgr;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public abstract class SocketBase
{
	/**
	 * 日志
	 */
	private static Logger m_logger = LoggerFactory.getLogger(SocketBase.class);
	
	/**
	 * 定时检测服务端、客户端状态定时器编号
	 */
	private int timerId;
	
	/**
	 * 服务端信息
	 */
	protected ServerInfo serverInfo;	
	
	/**
	 * 设置服务器信息，配置用
	 */
	public void setServerInfo(ServerInfo serverInfo) 
	{
		this.serverInfo = serverInfo;
	}

	/**
	 * 建立服务端、客户端连接
	 * 0.连接成功 1.拒绝连接 2.连接失败
	 */
	public Integer connect()
	{
		Integer retValue = 0;
		retValue = connectServer();
		initializeServer();
		
		timerId = TimerMgr.getInstance().setTimer(this, "checkServerStatus", serverInfo.getInterval(), false);
		if (timerId == 0) 
		{
			m_logger.error("Set check server status timer failed");
		}
		
		return retValue;
	}

	/**
	 * 建立服务端、客户端连接
	 * 0.连接成功 1.拒绝连接 2.连接失败
	 */
	public Integer connectNoHearbeat()
	{
		Integer retValue = 0;
		retValue = connectServer();
		initializeServer();

		//timerId = TimerMgr.getInstance().setTimer(this, "checkServerStatus", serverInfo.getInterval(), false);
		//if (timerId == 0)
		//{
		//	m_logger.error("Set check server status timer failed");
		//}

		return retValue;
	}
	
	/**
	 * 断开服务端、客户端连接
	 */
	public CloseFuture disConnect()
	{
		if (timerId != 0)
		{
			TimerMgr.getInstance().killTimer(timerId);
		}
		return disConnectServer();
	}
	
	/**
	 * 定时检查连接状态
	 */
	public void checkServerStatus() 
	{
		//获取当前时间
		long timeStamp = new Date().getTime();
		
		//比较当前时间与最后一次心跳时间，若大于指定时间则认为心跳超时
		if ((timeStamp - serverInfo.getTimeStamp()) > serverInfo.getTimeout()) 
		{
			m_logger.warn("Data receive from connection is time out, reconnect");
			
			serverInfo.setStatus(false);
			
			//重新建立连接
			disConnectServer();
			connectServer();
			initializeServer();
		}
	}
	
	/**
	 * 连接服务器
	 * 0.连接成功 1.拒绝连接 2.连接失败
	 */
	protected Integer connectServer()
  	{	
  		return 0;
  	}
  	
	/**
	 * 建立连接后的初始化接口，由子类实现
	 */
	protected void initializeServer()
	{		
	}
	
    /**
     * 断开连接接口，由子类实现
     */
	protected CloseFuture disConnectServer()
  	{
  		return null;
  	}
  	
  	/**
  	 * 响应消息处理接口，由子类实现
  	 */
    public void onMessageReceive(SocketMessage message, IoSession session)
    {
    }
    
    /**
     * 接收到的Socket缓冲流处理接口，需要进行拆包合包操作，由子类实现
     */
    public boolean handleBuffer(IoBuffer in, ProtocolDecoderOutput out, IoSession session)
    {
    	return false;
    }
    
  	/**
  	 * 发送请求消息接口，由子类实现
  	 */
  	public void sendMessage(SocketMessage message, IoSession session)
  	{
  	}
}
